/*  ------------------------------------------------------------------------
	 NQ Common Services Library
	 
	 Homepage: http://www.awzhome.de/
	 ------------------------------------------------------------------------
	 
	 The contents of this file are subject to the Mozilla Public License
	 Version 1.1 (the "License"); you may not use this file except in
	 compliance with the License. You may obtain a copy of the License at
	 http://www.mozilla.org/MPL/
	 
	 Software distributed under the License is distributed on an "AS IS"
	 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	 License for the specific language governing rights and limitations
	 under the License.
	
	 The Original Code is code of NQ Common Services Library.

	 The Initial Developer of the Original Code is Andreas Weizel.
	 Portions created by the Initial Developer are
	 Copyright (C) 2006-2011 Andreas Weizel. All Rights Reserved.
	 
	 Contributor(s): (none)
	 
	 Alternatively, the contents of this file may be used under the terms
	 of the GNU General Public License Version 2.0 or later (the "GPL"),
	 or the GNU Lesser General Public License Version 2.1 or later (the
	 "LGPL"), in which case the provisions of the GPL or the LGPL are
	 applicable instead of those above. If you wish to allow use of your
	 version of this file only under the terms of the GPL or the LGPL and
	 not to allow others to use your version of this file under the MPL,
	 indicate your decision by deleting the provisions above and replace
	 them with the notice and other provisions required by the GPL or the
	 LGPL. If you do not delete the provisions above, a recipient may use
	 your version of this file under the terms of any of the MPL, the GPL
	 or the LGPL.
	 ------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Text;
using AWZhome.NQ.Core;
using AWZhome.NQ.Core.Fluent;
using System.IO;
using System.Reflection;
using System.Windows;

namespace AWZhome.NQ.CommonServices
{
	[NQExportedService]
	[NQServiceAttachment(CommonAttachLists.MainContainer_Startup)]
	internal class NQUpdateGUIService
	{
		private IContainer _servContainer = null;
		private IUpdateManager _servUpdate;
		private IResourceManager _servRes;
		private IWizardDialogViewManager _servWizard;
		private bool _updateInfoDownload = false;
		private bool _updateSourcesAvailable;

		public NQUpdateGUIService(IContainer parent)
		{
			_servContainer = parent;

			// Create menu items
			Stream xmlstream = Assembly.GetExecutingAssembly().GetManifestResourceStream("AWZhome.NQ.CommonServices.menudef.Update.xml");
			_servContainer.BarService.CreateItemsFromXml(xmlstream);
			xmlstream.Close();

			// Init services
			_servRes = ServiceCore
				.Get<Services.IResourceService>()
				.To;
			_servUpdate = ServiceCore
				.Get<Services.IUpdateService>()
				.To;

			// Set event handlers
			_servContainer.BarService.ItemClicked += BarService_ItemClicked;
			_servUpdate.UpdateProgress += _servUpdate_UpdateProgress;
			_servUpdate.UpdateError += _servUpdate_UpdateError;
		}

		#region Other private methods

		private void BarService_ItemClicked(object sender, BarItemClickedEventArgs e)
		{
			switch (e.Item.ItemKey)
			{
				case "mnuHelp.Update":
					// Show updater wizard
					CreateWizard();
					break;
			}
		}

		private void _servUpdate_UpdateProgress(object sender, UpdateProgressEventArgs e)
		{
			if (e.ProgressType == UpdateProgressEventType.Ready)
			{
				if (_updateInfoDownload)
				{
					_updateInfoDownload = false;
					if (_servWizard != null)
					{
						_servWizard.CurrentViewIndex = 1;
					}
				}
			}
		}

		private void _servUpdate_UpdateError(object sender, UpdateErrorEventArgs e)
		{
			// Error messages are created in the wizard views directly
			_updateInfoDownload = false;
		}

		private void CreateWizard()
		{
			_servWizard = ServiceCore
				.Create<Services.IWizardDialogService>()
				.DependentOn<IContainer>(_servContainer)
				.To;

			_servWizard.AdditionalButtonClicked += _servWizard_AdditionalButtonClicked;
			_servWizard.WizardClosed += _servWizard_WizardClosed;
			_servWizard.ActiveViewChanged += _servWizard_ActiveViewChanged;

			_servWizard.WizardCaption = _servRes.GetResString("NQCS", "UpdateDialog.Title");
			_servWizard.WizardTitle = _servRes.GetResString("NQCS", "UpdateDialog.Label.SubTitle");
			_servWizard.AdditionalButtonText = _servRes.GetResString("NQCS", "UpdateDialog.Button.ReloadUpdateList");

			// Create wizard pages
			IView progressView = ServiceCore
				.Create<Services.IUpdateProgressViewService>()
				.DependentOn<ISession>(null)
				.To;
			progressView.Initialize("updateProgress");
			progressView.DisplayMode = ViewDisplayMode.InClientArea;

			IView selectView = ServiceCore
				.Create<Services.IUpdateSelectViewService>()
				.DependentOn<ISession>(null)
				.To;
			selectView.Initialize("updateSelection");
			selectView.DisplayMode = ViewDisplayMode.InClientArea;

			IView jobProgressView = ServiceCore
				.Create<Services.IUpdateProgressViewService>()
				.DependentOn<ISession>(null)
				.To;
			jobProgressView.Initialize("updateJobProgress");
			jobProgressView.DisplayMode = ViewDisplayMode.InClientArea;

			_servWizard.AddView(progressView);
			_servWizard.AddView(selectView);
			_servWizard.AddView(jobProgressView);

			// If no update information has been downloaded yet, do it now
			_updateSourcesAvailable = true;
			if (!_servUpdate.UpdateInformationLoaded)
			{
				if (MessageBox.Show(
					_servRes.GetResString("NQCS", "AppMsg.Update.RefreshUpdateInfo"),
					_servRes.GetResString("NQCS", "UpdateDialog.Title"),
					MessageBoxButton.YesNo, MessageBoxImage.Question
					) == MessageBoxResult.Yes)
				{
					_updateSourcesAvailable = DownloadUpdateInfo();
					if (!_updateSourcesAvailable)
					{
						// Show second page (release selection) and disable the "refresh" button
						_servWizard.CurrentViewIndex = 1;
					}
				}
				else
				{
					// Show second page (release selection)
					_servWizard.CurrentViewIndex = 1;
				}
			}
			else
			{
				// Show second page (release selection)
				_servWizard.CurrentViewIndex = 1;
			}

			_servWizard.ShowAdditionalButton = _updateSourcesAvailable;
			_servWizard.ShowWizard();
		}

		private void _servWizard_ActiveViewChanged(object sender, ActiveViewChangedEventArgs e)
		{
			int newIndex = (e.NewView != null) ? _servWizard.IndexOfView(e.NewView) : -1;
			int oldIndex = (e.OldView != null) ? _servWizard.IndexOfView(e.OldView) : -1;

			// Control the buttons dependent on the active page
			switch (newIndex)
			{
				case 0:
					// Buttons for the update information progress page
					_servWizard.ShowAdditionalButton = false;
					_servWizard.GoBackEnabled = false;
					_servWizard.CancelEnabled = true;
					break;

				case 1:
					_servWizard.ShowAdditionalButton = _updateSourcesAvailable;
					_servWizard.GoBackEnabled = false;
					_servWizard.CancelEnabled = true;
					break;

				case 2:
					_servWizard.CancelEnabled = false;
					break;
			}

			// If the page changes from selection page to job progress page, start the job
			if ((oldIndex == 1) && (newIndex == 2))
			{
				// Ask if user really wants to execute the update job
				if (MessageBox.Show(_servRes.GetResString("NQCS", "AppMsg.Update.BeginUpdate"),
					_servWizard.WizardCaption,
					MessageBoxButton.YesNo, MessageBoxImage.Question)
					== MessageBoxResult.Yes)
				{
					// User wants to start the update job, so start the update job :-)
					try
					{
						_servUpdate.ExecuteUpdateJob();
					}
					catch (UpdateException nqex)
					{
						if (nqex.ErrorType == UpdateExceptionType.NotReady)
						{
							MessageBox.Show(_servRes.GetResString("NQCS", "AppMsg.Update.EmptyJobList"),
								_servWizard.WizardCaption,
								MessageBoxButton.OK, MessageBoxImage.Exclamation);
						}

						// Go back to old page
						_servWizard.CurrentViewIndex = oldIndex;
					}
				}
				else
				{
					// Go back to old page
					_servWizard.CurrentViewIndex = oldIndex;
				}
			}
		}

		private void _servWizard_WizardClosed(object sender, EventArgs e)
		{
			_servWizard.AdditionalButtonClicked -= _servWizard_AdditionalButtonClicked;
			_servWizard.WizardClosed -= _servWizard_WizardClosed;
			_servWizard.ActiveViewChanged -= _servWizard_ActiveViewChanged;
			_servWizard = null;
		}

		private void _servWizard_AdditionalButtonClicked(object sender, EventArgs e)
		{
			// Ask user if he really wants to continue
			if (_servUpdate.JobList.Count > 0)
			{
				if (MessageBox.Show(
					_servRes.GetResString("NQCS", "AppMsg.Update.JobListClearedOnRefreshWarning"),
					_servRes.GetResString("NQCS", "UpdateDialog.Title"),
					MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
				{
					DownloadUpdateInfo();
				}
			}
		}

		private bool DownloadUpdateInfo()
		{
			bool result = true;

			// Go back to first page and restart download
			try
			{
				_servWizard.CurrentViewIndex = 0;
				_updateInfoDownload = true;
				_servUpdate.CheckForUpdates();
			}
			catch (UpdateException ex)
			{
				switch (ex.ErrorType)
				{
					case UpdateExceptionType.Busy:
					case UpdateExceptionType.NotReady:
						MessageBox.Show(_servRes.GetResString("NQCS", "AppMsg.Update.Busy"),
							_servWizard.WizardCaption, MessageBoxButton.OK, MessageBoxImage.Warning);
						break;

					case UpdateExceptionType.NoSources:
						MessageBox.Show(_servRes.GetResString("NQCS", "AppMsg.Update.NoSources"),
							_servWizard.WizardCaption, MessageBoxButton.OK, MessageBoxImage.Warning);
						result = false;
						break;

					default:
						MessageBox.Show(_servRes.GetResString("NQCS", "AppMsg.Update.GeneralError", ex.Message),
							_servWizard.WizardCaption, MessageBoxButton.OK, MessageBoxImage.Warning);
						break;
				}
			}

			return result;
		}

		#endregion
	}
}
